
const todos = {
  namespaced: true,

  state: {
    list: JSON.parse(localStorage.getItem("vuex-todos")) || [],
    
    type: 'all'
  },

  mutations: {
    //切换任务状态
    changeFn(state, id){
      const obj = state.list.find(item => item.id === id)
      obj.isDone = !obj.isDone
    },

    del(state, id){
      state.list = state.list.filter(item => item.id !== id)
    },

    add(state, name){
      state.list.unshift({
        id: parseInt(Math.random()*999+1),
        name,
        isDone: false
      })
    },

    changeAll(state, val){
      state.list.forEach(item => item.isDone = val)
    },

    clearFn(state){
      state.list = state.list.filter(item => !item.isDone)
    },

    changeDone(state, type){
      state.type = type
    }

  },

  getters: {
    sum(state){
      return state.list.filter(item => !item.isDone).length
    },

    showList(state){
      if(state.type === 'active'){
        return state.list.filter(item => !item.isDone)
      } else if(state.type === 'complete'){
        return state.list.filter(item => item.isDone)
      } else {
        return state.list
      }
    }
  }
}

export default todos